package com.higgins.eventtracking.server;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.higgins.eventtracking.server.dataModel.Asset;

@SuppressWarnings("serial")
public class CheckForStartOfMonthServlet extends HttpServlet	{
	private static final Logger log = Logger.getLogger(CheckForStartOfMonthServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)	throws IOException	{
		log.info("checkForStartOfMonthServlet is running!!");
		if (DateUtility.isFirstWeekOfMonth(new Date()))		{
			log.info("First week of the month confirmed!!!");
			addProfitToSavings();
			serviceLoans();
		}
	}
	
	private void addProfitToSavings()	{
		IncomeSettingsDataService incomeService = new IncomeSettingsDataService();
		AssetTrackingDataService assetService = new AssetTrackingDataService();
		FinanceTrackingDataService financeService = new FinanceTrackingDataService();
		
		try	{
			incomeService.openPersistenceManager();
			assetService.openPersistenceManager();
			financeService.openPersistenceManager();
			
			log.info("1 of 3 - Profit Calculation Begun!!");
			Double income = Double.parseDouble(incomeService.retrieveIncome());
			Double fixedOutgoing = Double.parseDouble(incomeService.retrieveOutgoing()) + 
										Double.parseDouble(incomeService.retrieveSeverableOutgoing());
			Double monthsTotalExpenses = financeService.getTotalExpensesThisMonthJustGone(true);
			Double remaining = income - fixedOutgoing - monthsTotalExpenses;
			log.info("2 of 3 - Profit Calculation Complete!!");
			assetService.addAsset(remaining.toString(), "Silver");
			log.info("3 of 3 - Profit hasbee added to the asset service!!");
		} catch (Exception e)	{
			log.severe(e.toString());
		} finally {
			incomeService.closePersistenceManager();
			assetService.closePersistenceManager();
			financeService.closePersistenceManager();
		}
	}
	private void serviceLoans()	{
		AssetTrackingDataService assetService = new AssetTrackingDataService();
		try	{
			log.info("1 of 2 - Loan Calculation Begun!!");
			assetService.openPersistenceManager();
			List<Asset> loans = assetService.retrieveLoans();
			for (Asset loan:loans)	{
				Double amount = loan.getAmount();
				Double repayment = loan.getMonthlyRepayment();
				Double interest = loan.getMonthlyInterest();
				if (amount > 0.0)	{
					amount-= repayment;
					loan.setAmount(amount);
					assetService.updateAsset(loan);
					
					assetService.addAsset(repayment+interest, loan.getAccountRepayment());
				}
			}
			log.info("2 of 2 - Loan Calculation Complete!!");			
		} catch (Exception e)	{
			log.severe(e.toString());
		} finally {
			assetService.closePersistenceManager();
		}
	}
}
